package com.csy.rabbit.admin.service.impl;

import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csy.rabbit.admin.dto.AdminLoginDTO;
import com.csy.rabbit.admin.entity.Admin;
import com.csy.rabbit.admin.mapper.AdminMapper;
import com.csy.rabbit.admin.service.AdminService;
import com.csy.rabbit.commit.exception.BusinessException;
import com.csy.rabbit.commit.exception.EmailNonExistentException;
import com.csy.rabbit.admin.util.BCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author csy
 * @since 2022-12-08
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    private String key="1234";

    @Override
    public String login(AdminLoginDTO adminLoginDTO) {
        System.out.println(bCryptPasswordEncoder.encode(adminLoginDTO.getPassword()));
        //查询并判断用户名是否正确
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getEmail, adminLoginDTO.getEmail());
        Admin amdin = this.getOne(wrapper);

        if(amdin==null){
          throw new EmailNonExistentException("邮箱不存在");
        }
        if(!bCryptPasswordEncoder.matches(adminLoginDTO.getPassword(),amdin.getPassword())){
            throw new BusinessException("密码错误");
        }
        //签发token
        String token = JWT.create()
                .setPayload("adminId", amdin.getAdminId())
                .setPayload("time", System.currentTimeMillis())
                .setKey(key.getBytes())
                .sign();

        redisTemplate.opsForValue().set(token,"1",20, TimeUnit.SECONDS);
        return token;
    }

    @Override
    public Boolean method(String token) {
        //判断token是否过期
        if(!redisTemplate.hasKey(token)){
            throw new BusinessException("token过期");
        }
        //否则存在redis里面
        String s = redisTemplate.opsForValue().get(token);
        //开始校验
        boolean result = JWT.of(s).setKey(key.getBytes()).verify();
        //校验成功设置时间
        if(result){
            redisTemplate.expireAt(token,new Date(System.currentTimeMillis()+20000));
        }
        return result;
    }
}
